package fileController

import (
	"CMETO/conf"
	"fmt"
	"net/http"
	"path"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
)

type FileController struct{}

// 单文件上传方法绑定
func (f FileController) SingleUpload(ctx *gin.Context) {
	file, err := ctx.FormFile("file")
	if err != nil {
		ctx.String(http.StatusOK, "上传失败")
	}
	filename := strconv.FormatInt(time.Now().UnixMilli(), 10) + file.Filename
	dst := path.Join("./static/upload/", filename)
	fmt.Println(dst)
	if ok := ctx.SaveUploadedFile(file, dst); ok != nil {
		ctx.String(http.StatusOK, fmt.Sprintf("'%s' fail!", err))
	}
	ctx.JSON(http.StatusOK, gin.H{
		"url": dst,
	})
}

// 上传到七牛云
func (f FileController) SingleToQiNiu(ctx *gin.Context) {
	fileHeader, err1 := ctx.FormFile("file")
	if err1 != nil {
		ctx.String(http.StatusOK, "上传失败")
	}
	AccessKey, SerectKey, Bucket, _ := conf.Conf{}.LoadConfig()
	key := "avatar/IMG_" + strconv.FormatInt(time.Now().UnixMilli(), 10) + fileHeader.Filename
	putPlicy := storage.PutPolicy{
		Scope:   Bucket,
		SaveKey: key,
	}
	mac := qbox.NewMac(AccessKey, SerectKey)
	upToken := putPlicy.UploadToken(mac)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuanan,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": fileHeader.Filename,
		},
	}
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	file, _ := fileHeader.Open()
	defer file.Close()
	err := formUploader.PutWithoutKey(ctx, &ret, upToken, file, fileHeader.Size, &putExtra)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"err": err,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"result": ret,
	})
}

// 从七牛云获取文件信息
func (f FileController) GetImages(ctx *gin.Context) {
	AccessKey, SerectKey, Bucket, _ := conf.Conf{}.LoadConfig()
	mac := qbox.NewMac(AccessKey, SerectKey)
	cfg := storage.Config{
		UseHTTPS: false,
	}
	cfg.Region = &storage.ZoneHuanan
	bucketManager := storage.NewBucketManager(mac, &cfg)
	limit := 1000
	prefix := "avatar/IMG"
	delimiter := ""
	marker := ""
	var result = make([]string, 0)
	for {
		entries, _, nextMarker, hasNext, err := bucketManager.ListFiles(Bucket, prefix, delimiter, marker, limit)
		if err != nil {
			fmt.Println("list error,", err)
			break
		}
		for _, entry := range entries {
			result = append(result, entry.Key)
		}
		if hasNext {
			marker = nextMarker
		} else {
			break
		}
	}
	ctx.JSON(http.StatusOK, gin.H{
		"result": result,
	})
}

// 删除七牛云的某张图片
func (f FileController) DeleteFile(ctx *gin.Context) {
	AccessKey, SerectKey, Bucket, _ := conf.Conf{}.LoadConfig()
	mac := qbox.NewMac(AccessKey, SerectKey)
	cfg := storage.Config{
		UseHTTPS: false,
	}
	cfg.Region = &storage.ZoneHuanan
	bucketManager := storage.NewBucketManager(mac, &cfg)
	key := ctx.Query("key")
	err := bucketManager.Delete(Bucket, key)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"msg":  "失败",
			"code": "400",
		})
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"msg":  "成功",
			"code": "200",
		})
	}
}
